import 'package:async/async.dart';
import 'package:boss/models/material.dart' as material;
import 'package:boss/provider/material_provider.dart';
import 'package:boss/ui/widget/loader/loader.dart';
import 'package:hi_common/hi_common.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

import 'material_picker_item.dart';

class MaterialPickerList extends StatelessWidget {
  Future<Result<List<material.Material>>> _loadTask(BuildContext context) async {
    var materialProvider = Provider.of<MaterialProvider>(
      context,
      listen: false,
    );
    return await materialProvider.initData();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.only(
        top: 10.w,
      ),
      child: Loader<List<material.Material>>(
        loadTask: () => _loadTask(context),
        builder: (context) {
          return Consumer<MaterialProvider>(
            builder: (context, materialProvider, child) {
              return ListView.builder(
                shrinkWrap: true,
                physics: NeverScrollableScrollPhysics(),
                padding: EdgeInsets.symmetric(
                  horizontal: 20.w,
                ),
                itemBuilder: (context, index) {
                  var current = materialProvider.searchMaterials[index];
                  var isSelected = materialProvider.selectedMaterials.any((item) => item.id == current.id);

                  return MaterialPickerItem(
                    data: current,
                    isSelected: isSelected,
                    onTap: () {
                      materialProvider.toggleSelected(current);
                    },
                  );
                },
                itemCount: materialProvider.searchMaterials.length,
              );
            },
          );
        },
      ),
    );
  }
}
